<?php

namespace App\Repositories;

use App\Models\Menu;
use App\Models\RoleMenu;
use App\Exceptions\InvalidException;
class MenuRepo
{
    public function allMenus()
    {
        $menus = Menu::all()->toArray();

        return self::buildMenu($menus,'children');
    }
    public function getMenus($role_id,$keyCode="child")
    {
        $menu_ids = RoleMenu::where('role_id',$role_id)->select('menu_id')->get()->toArray();
        if(!$menu_ids) return [];
        $menu_ids_arr = array_column($menu_ids, 'menu_id');
     

        $menus = Menu::whereIn('id',$menu_ids_arr)->select('id','name','path','pid','icon')->orderBy('order','desc')->get()->toArray();

        return self::buildMenu($menus,$keyCode);
    }

    public static function buildMenu(array $menu,$keyCode="child") 
    {
        if(!$menu) return [];

        $first =[];
        $other = [];
        //筛选出第一层
        foreach($menu as $key=>$item) {
            if($item['pid'] == 0) {
                $first[] = $item;
            } else {
                $other[] = $item;
            }
        }

        foreach($first as &$pmenu) {
            foreach($other as $cmenu) {
                if($cmenu['pid'] == $pmenu['id']) {
                    $pmenu[$keyCode][] = $cmenu;
                }
            }
        }

        return $first;

    }
    public function addMenu(array $data)
    {
        try{
            Menu::create($data);
        } catch(\Exception $e) {
            throw new InvalidException($e->getMessage());
        }
    }
    public function getOneById($id) 
    {
        return Menu::where('id',$id)->first();
    }
    public function delMenu($id)
    {
    	$menu = $this->getOneById($id);

    	if(!$menu) {
    		throw new  InvalidException("Error Processing Request");
    	}

    	try{
    		$menu->delete();
    	} catch(\Exception $e) {
    		throw new InvalidException($e->getMessage());
    	}
    	
    }

    public function editMenu($data)
    {
        $menu = $this->getOneById($data['id']);
        if(!$menu) {
            throw new  InvalidException("菜单不存在");
        }
        try {
            $menu->pid   = empty($data['pid']) ? 0 : $data['pid'];
            $menu->name  = $data['name'];
            $menu->path  = $data['path'];
            $menu->icon  = $data['icon'];
            $menu->title = $data['title'];
            $menu->order  = $data['order'];
            $menu->save();
        }catch(\Exception $e) {
            throw new  InvalidException("编辑失败");
        }
    }

    
}